package model

import "gorm.io/gorm"

type User struct {
	UserID         string   `json:"user_id" gorm:"column:user_id"`                   // 用户账号
	Email          string   `json:"email" gorm:"column:email"`                       // 用户邮箱
	Phone          *int64   `json:"phone" gorm:"column:phone"`                       // 手机号
	Wechat         string   `json:"wechat" gorm:"column:wechat"`                     // 微信id
	Password       string   `json:"password" gorm:"column:password"`                 // 用户密码
	Salt           string   `json:"salt" gorm:"column:salt"`                         // 密码盐
	Role           string   `json:"role" gorm:"column:role"`                         // 权限
	UserName       string   `json:"user_name" gorm:"column:user_name"`               // 用户名称
	AvatarUrl      string   `json:"avatar_url" gorm:"column:avatar_url"`             // 用户头像
	Motto          string   `json:"motto" gorm:"column:motto"`                       // 用户描述
	CreditScore    *float64 `json:"credit_score" gorm:"column:credit_score"`         // 信誉分
	IpAddress      string   `json:"ip_address" gorm:"column:ip_address"`             // ip地址
	CreateIp       string   `json:"create_ip" gorm:"column:create_ip"`               // 注册时的ip地址
	LastOnlineTime *int64   `json:"last_online_time" gorm:"column:last_online_time"` // 最后在线时间
	DeleteTime     *int64   `json:"delete_time" gorm:"column:delete_time"`           // 注销时间
	Enable         *int8    `json:"enable" gorm:"column:enable"`                     // [0: 注销用户 1:正常用户]
	CreateTime     *int64   `json:"create_time" gorm:"column:create_time"`           // 创建时间
}

func (m *User) TableName() string {
	return "user"
}
func GetUserColumn() string {
	return "u.user_id, u.email, u.phone, u.wechat," +
		" u.password, u.salt, u.`role`, u.user_name, u.avatar_url, u.motto," +
		" u.last_online_time, u.ip_address, u.credit_score, u.enable, u.delete_time, u.create_time, u.create_ip"
}

func GetUserByPrivate(column string, userId string, db *gorm.DB) (User, error) {
	var users User
	query := db.Select(column).Where("u.user_id = ?", userId).Table("user as u")
	result := query.Find(&users)
	return users, result.Error
}

func GetUserLoginDetail(column string, account string, method int, db *gorm.DB) (User, error) {
	var users User
	query := db.Select(column).Table("user as u")
	switch method {
	case 1:
		query.Where("u.email = ?", account)
	case 2:
		query.Where("u.phone = ?", account)
	case 3:
		query.Where("u.wechat = ?", account)
	case 4:
		query.Where("u.telegram = ?", account)
	case 5:
		query.Where("u.qq = ?", account)
	case 6:
		query.Where("u.gitee = ?", account)
	}
	result := query.Find(&users)
	return users, result.Error
}

func UpdateUserDetail(db *gorm.DB, dataMap map[string]interface{}) error {
	result := db.Model(&User{}).Where("user_id = ?", dataMap["user_id"]).Updates(dataMap)
	return result.Error
}

func InsertUserDetail(db *gorm.DB, user User) error {
	result := db.Save(&user)
	return result.Error
}
